package com.rankeiot.platform.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.rankeiot.core.Current;
import com.rankeiot.core.anno.Auth;
import com.rankeiot.core.data.LocalizedMessage;
import com.rankeiot.core.data.UserInfo;
import com.rankeiot.core.data.response.Resp;
import com.rankeiot.core.sqltoy.Sql;
import com.rankeiot.platform.domain.User;
import com.rankeiot.platform.domain.WxUser;
import com.rankeiot.platform.service.UserService;
import com.rankeiot.platform.service.WxOpenService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 备注
 * 1：在 微信开放平台 加一个 网站应用，在应用详情里确认是否获得微信登录权限
 * 2：在应用详情里 获取这个网站应用的appid和appsecret
 * 3: 在应用详情-开发信息里配置域名（本地测试可用花生壳） *
 */

@RestController
@Tag(name = "WXLogin")
@RequestMapping("/WXLogin")
@RequiredArgsConstructor
@Slf4j
public class WXLoginController {

    final private SqlToyLazyDao dao;
    final private WxOpenService wxOpenService;
    final private UserService userService;
    @AllArgsConstructor
    @Getter
    enum Messages implements LocalizedMessage {
        AuthorizationError("Authorization error","授权出错");
        private final String en;
        private final String zh;
    }

    @Operation(summary = "userInfo")
    @GetMapping("/userInfo")
    public ResponseEntity userInfo(HttpServletRequest request, String code) throws IOException {
        Map result = wxOpenService.oauth2getAccessToken(code);
        if (result == null) {
            return ResponseEntity.status(400).body(Messages.AuthorizationError);
        }
        if(result.get("openid") == null) {
            return ResponseEntity.status(400).body(Messages.AuthorizationError);
        }
        String openId = result.get("openid").toString();
        String unionId = result.get("unionid").toString();
        String accessToken = result.get("access_token").toString();
        String sql = Sql.select("*")
                .from(WxUser.TABLE)
                .eq(WxUser.Fields.openid)
                .toString();
        WxUser wxUser = new WxUser();
        wxUser.setOpenid(openId);
        List<WxUser> bySql = dao.findBySql(sql, wxUser);
        //未注册
        if (CollectionUtil.isEmpty(bySql)) {
            //获取用户微信的基本信息
            Map userinfo = wxOpenService.userinfo(openId,accessToken);
            WxUser bindWx = new WxUser();
            bindWx.setOpenid(openId);
            bindWx.setUnionId(unionId);
            if (userinfo != null && userinfo.containsKey("nickname")){
                bindWx.setNickname(userinfo.get("nickname").toString());
                bindWx.setSex(userinfo.get("sex").toString());
                bindWx.setProvince(userinfo.get("province").toString());
                bindWx.setCity(userinfo.get("city").toString());
                bindWx.setCountry(userinfo.get("country").toString());
                bindWx.setHeadimgurl(userinfo.get("headimgurl").toString());
                bindWx.setPrivilege(userinfo.get("privilege").toString());
                //信息缓存到session里
                request.getSession().setAttribute(SystemLoginController.WXINFO_SESSIONKEY,bindWx);
            }
            //return Resp.ok(openId);
            return ResponseEntity.ok("<script>let e=new Event('loginReg');e.openId='"+openId+"';e.unionId='"+unionId+"';parent.dispatchEvent(e)</script>");
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setId(bySql.get(0).getUserId()+"");
        userInfo = dao.loadBySql("select * from t_user where id=:id",userInfo);
        if(ObjectUtil.isEmpty(userInfo)){
            Resp.fail(SystemController.Messages.UnknownError);
        }
        userInfo = userService.loadUserInfo(userInfo.getUsername(),null);
        Current.login(userInfo);

        return ResponseEntity.ok("<script>sessionStorage._token='"+userInfo.getToken()+"',parent.location.href='/';console.log('登录')</script>");
    }
    @Operation(summary = "登录后绑定微信")
    @GetMapping("/bindWx/{id}")
    public ResponseEntity bindWx(HttpServletRequest request, String code,@PathVariable("id") String id) throws IOException {
        Map result = wxOpenService.oauth2getAccessToken(code);
        if (result == null) {
            return ResponseEntity.status(400).body(Messages.AuthorizationError);
        }
        if(result.get("openid") == null) {
            return ResponseEntity.status(400).body(Messages.AuthorizationError);
        }
        String openId = result.get("openid").toString();
        String unionId = result.get("unionid").toString();
        String access_token = result.get("access_token").toString();
        String sql = Sql.select("*")
                .from(WxUser.TABLE)
                .eq(WxUser.Fields.openid)
                .toString();
        WxUser wxUser = new WxUser();
        wxUser.setOpenid(openId);
        List<WxUser> bySql = dao.findBySql(sql, wxUser);
       //openid已绑定微信
        if (CollectionUtil.isNotEmpty(bySql)) {
            return ResponseEntity.ok("<script>let e=new Event('bindErr');e.openId='"+openId+"';e.unionId='"+unionId+"';parent.dispatchEvent(e)</script>");
        } else{
            WxUser bindWx = new WxUser();
            bindWx.setOpenid(openId);
            bindWx.setUnionId(unionId);
            bindWx.setUserId(Long.parseLong(id));
            //获取用户微信的基本信息
            Map userinfo = wxOpenService.userinfo(openId,access_token);
            if (userinfo != null && userinfo.containsKey("nickname")){
                bindWx.setNickname(userinfo.get("nickname").toString());
                bindWx.setSex(userinfo.get("sex").toString());
                bindWx.setProvince(userinfo.get("province").toString());
                bindWx.setCity(userinfo.get("city").toString());
                bindWx.setCountry(userinfo.get("country").toString());
                bindWx.setHeadimgurl(userinfo.get("headimgurl").toString());
                bindWx.setPrivilege(userinfo.get("privilege").toString());
            }
            dao.save(bindWx);
            return ResponseEntity.ok("<script>let e=new Event('bindWxSuccess');e.openId='"+openId+"';e.unionId='"+unionId+"';parent.dispatchEvent(e)</script>");
        }
    }
    @Operation(summary = "解绑")
    @PostMapping("/unbind")
    public Resp unbind(){
        Map<String,Object> params = new HashMap<>();
        params.put("userid",Current.user().getId());
        dao.executeSql("delete from "+WxUser.TABLE+" where user_id = :userid",params);
        return Resp.ok();
    }
    /**
     * 当前登录用户是否已经绑定微信
     * @return
     * @throws IOException
     */
    @Operation(summary = "isbind")
    @PostMapping("/isbind")
    @Auth
    public Resp isbind() {
        String sql = Sql.select("*") .from(WxUser.TABLE)
                .eq(WxUser.Fields.userId)
                .toString();
        WxUser wxUser = new WxUser();
        wxUser.setUserId(Long.parseLong(Current.user().getId()));
        List<WxUser> bySql = dao.findBySql(sql, wxUser);
        Map<String, Object> result = new HashMap<>();
        result.put("isbind", "N");
        if (CollectionUtil.isNotEmpty(bySql)) {
            result.put("isbind","Y");
            result.put("info",bySql.get(0));
        }
        return Resp.of(result);
    }

    @Data
    public static class UserDto {
        private String code;
    }
}
